package com.lvandroid.play.player;

import android.media.MediaPlayer;
import android.view.ViewGroup;

import com.lvandroid.play.bean.AudioItem;
import com.lvandroid.play.util.LogUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class AudioPlayer extends AllRoundPlayer<ViewGroup, AudioItem> implements MediaPlayer.OnPreparedListener {

    private static final String TAG = "AudioPlayer";
    private MediaPlayer mPlayer;
    private boolean mAutoPlay = false;

    AudioPlayer() {
        mPlayItem = new AudioItem();
        mPlayer = new MediaPlayer();
    }

    @Override
    public void setDataSource(List source) {
        if(null == source || source.size() < 1) {
            throw new IllegalArgumentException("setDataSource error!");
        }
        LogUtil.i(TAG, "setDataSource : " + Arrays.toString(source.toArray()));

        setDataSource((String) source.get(0));
    }

    @Override
    public void setDataSource(String source) {
        LogUtil.i(TAG, "setDataSource : " + source);
        mPlayItem.url = source;
        try {
            mPlayer.setDataSource(source);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void start(List<String> source, ViewGroup display) {
        LogUtil.i(TAG, "start : " + source);
        setDataSource(source);
        start(mPlayItem.url);
    }

    @Override
    public void start(String source) {
        LogUtil.i(TAG, "start : " + source);
        setPrepareListener(null);
        setDataSource(source);
        prepare();
        mAutoPlay = true;
    }

    @Override
    public void setPrepareListener(OnPrepareListener l) {
        mExternalListener = l;
        mPlayer.setOnPreparedListener(this);
    }

    @Override
    public void prepare() {
        mPlayer.prepareAsync();
    }

    @Override
    public void start() {
        mPlayer.start();
    }

    @Override
    public void stop() {
        mPlayer.stop();
    }

    @Override
    public void pause() {
        mPlayer.pause();
    }

    @Override
    public void resume() {
        mPlayer.start();
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        LogUtil.i(TAG, "internal onPrepared : " + mediaPlayer);
        if(null != mExternalListener && !mAutoPlay) {
            mExternalListener.onPrepared(mPlayItem);
        } else {
            mAutoPlay = false;
            mediaPlayer.start();
        }
    }

}
